import { SchemaManage } from '@/components/SchemaComponent';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { ProcdefManageAPI } from '../common/type';
import { ProcdefManageContext, getTableColumns } from '../mconfig';
import { ViewFlowchartModal } from './ViewFlowchartModal';
import { message } from 'antd';
import { modifyStateService } from '../services';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';

export const ManageRightTableView: React.FC<ProcdefManageAPI.IManageTableView> = ({ searchRenderID }) => {
  const procdefManageTableRef: any = React.useRef();

  const tipErrorModalRef: any = React.useRef();
  /**
   * 获取上下文
   */
  const {
    rightTableProps: { dataSource, loading, getProcdefTableData, mapList, pagination, otherParams, searchList, reloadTableData },
    leftSelectKeys,
    curRes,
    dicFlowSelectRow,
    typeSelectRow,
  } = useContext(ProcdefManageContext);

  /**
   * 表格默认 参数
   */
  const tableParams = useMemo(() => {
    const dicFlowIdList = dicFlowSelectRow?.id ? dicFlowSelectRow?.id?.split('_') : '';
    return {
      orderType: typeSelectRow?.orderType,
      // businessCategory: dicFlowSelectRow?.id ? dicFlowSelectRow?.id : '',
      businessCategory: dicFlowSelectRow?.id ? dicFlowIdList?.[1] : '',
      // category: typeSelectRow?.id,
      category: dicFlowSelectRow?.id ? dicFlowIdList?.[0] : typeSelectRow?.id,
    };
  }, [dicFlowSelectRow, typeSelectRow]);

  useEffect(() => {
    if (leftSelectKeys && leftSelectKeys?.length > 0) {
      let tablePayload = {
        ...otherParams,
        ...tableParams,
      };
      getProcdefTableData({ ...tablePayload });
    }
  }, [leftSelectKeys]);

  /**
   * 查看流程图
   */
  const [flowchartModal, setFlowchartModal] = useState<any>({
    isShowModal: false,
    checkRowObj: {},
  });

  /**
   * 是否打开禁用提示框
   */
  const [disableTipModal, setDisableTipModal] = useState<any>({
    isShowModal: false,
    checkRowObj: {},
  });

  /* 切换方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    if (key) {
      getProcdefTableData({ ...params, ...searchValues });
    }
  };

  /**
   * 重置搜索表单方法
   */
  const onReset = (values: any) => {
    getProcdefTableData({ ...tableParams, ...values });
  };

  /**
   * 搜索列表
   */
  const onSearch = (request: ProcdefManageAPI.IGridRequestType) => {
    getProcdefTableData({ ...otherParams, ...request });
  };

  /**
   * 分页change 方法
   */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getProcdefTableData({ ...otherParams, pageSize, current, ...params });
  };

  /**
   * 修改流程状态接口回调
   * suspendState
   */
  const modifyStateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadTableData();
      if (disableTipModal?.isShowModal) {
        tipErrorModalRef?.current?.onCloseModal();
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 修改状态接口
   */
  const { modifyStateRun, modifyStateLoading } = modifyStateService(modifyStateCallback);

  /**
   * 表格操作按钮点击方法
   */
  const onOptClick: ProcdefManageAPI.IOperationClick = {
    onView: (resObj: Record<string, any>) => {
      setFlowchartModal({
        isShowModal: true,
        checkRowObj: resObj,
      });
    },
    onChange: (resObj: Record<string, any>, checked: boolean) => {
      if (checked) {
        let params = {
          id: resObj?.id,
          suspendState: resObj?.suspendState,
        };
        modifyStateRun(params);
      } else {
        setDisableTipModal({
          isShowModal: true,
          checkRowObj: resObj,
        });
      }
    },
  };

  /**
   * 获取columns方法
   */
  const columns: Record<string, any>[] = React.useMemo(() => {
    return getTableColumns(curRes, onOptClick);
  }, [curRes]);

  return (
    <>
      <SchemaManage
        ref={procdefManageTableRef}
        searchProps={{
          switchList: [], //头部切换列表
          searchList, //搜索表单列表
          onReset, //重置
          onSwitch, //头部切换
          onSearch, //搜索方法
        }}
        actionList={[]} //Table头部操作按钮列表
        searchDrawerRender={searchRenderID}
        tableProps={{
          // table 表格属性
          columns,
          dataSource,
          loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange, //分页change方法
        }}
      />

      {/* 查看流程图 */}
      {flowchartModal?.isShowModal && (
        <ViewFlowchartModal
          visible={flowchartModal?.isShowModal}
          onClose={() => {
            setFlowchartModal(false);
          }}
          checkRowObj={flowchartModal?.checkRowObj}
        />
      )}

      {/* 禁用提示框 */}
      {disableTipModal?.isShowModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={modifyStateLoading}
          onClose={() => {
            setDisableTipModal({
              isShowModal: false,
              checkRowObj: {},
            });
          }}
          modalOnOK={() => {
            let params = {
              id: disableTipModal?.checkRowObj?.id,
              suspendState: disableTipModal?.checkRowObj?.suspendState,
            };
            modifyStateRun(params);
          }}
          modalTip={'禁用后，该流程将不可使用，是否确认禁用？'}
        />
      )}
    </>
  );
};
